package com.quanxiaoha.weblog.common.utils;

import com.quanxiaoha.weblog.common.domain.dos.UserDO;
import com.quanxiaoha.weblog.common.domain.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * 用户上下文工具类
 * 用于获取当前登录用户信息
 */
@Slf4j
@Component
public class UserContextHolder {

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取当前登录用户名
     * @return 用户名
     */
    public String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return authentication.getName();
        }
        return null;
    }

    /**
     * 获取当前登录用户ID
     * @return 用户ID
     */
    public Long getCurrentUserId() {
        String username = getCurrentUsername();
        if (username != null) {
            UserDO userDO = userMapper.findByUsername(username);
            if (userDO != null) {
                return userDO.getId();
            }
        }
        return null;
    }

    /**
     * 获取当前登录用户信息
     * @return 用户信息
     */
    public UserDO getCurrentUser() {
        String username = getCurrentUsername();
        if (username != null) {
            return userMapper.findByUsername(username);
        }
        return null;
    }

    /**
     * 检查当前用户是否为管理员
     * @return true-管理员，false-普通用户
     */
    public boolean isAdmin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getAuthorities() != null) {
            return authentication.getAuthorities().stream()
                    .anyMatch(authority -> "ROLE_ADMIN".equals(authority.getAuthority()));
        }
        return false;
    }
}
